import { defineStore } from 'pinia'

import {
  postUserListData,
  deleteUserById,
  newUserData,
  editUserData,
  postPageListData,
  deletePageById,
  newPageData,
  editPageData
} from '@/service/main/system/system'
import type { ISystemState } from './type'
import useMainStore from '../main/main'

const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    usersList: [],
    usersTotalCount: 0,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    async postUserListAction(querryInfo: any) {
      const res = await postUserListData(querryInfo)
      // console.log(res.data)
      const { totalCount, list } = res.data
      this.usersList = list
      this.usersTotalCount = totalCount
    },
    async deleteUserByIdAction(id: number) {
      // 1.删除数据操作
      const deleteResult = await deleteUserById(id)
      // console.log(deleteResult)

      // 2.重新请求新的数据
      this.postUserListAction({ offset: 0, size: 10 })
    },
    async newUserDataAction(userInfo: any) {
      // 1.创建新的用户
      const newResult = await newUserData(userInfo)
      console.log(userInfo)

      // 2.重新请求新的数据
      this.postUserListAction({ offset: 0, size: 10 })
    },
    async editUserDataAction(id: number, userInfo: any) {
      // 1.编辑用户的数据
      const editResult = await editUserData(id, userInfo)
      console.log(editResult)

      // 2.重新请求新的数据
      this.postUserListAction({ offset: 0, size: 10 })
    },

    // 重构，针对页面顺序进行增删改查
    // 查询
    async postPageListAction(pageName: string, querryInfo: any) {
      const pageListRes: any = await postPageListData(pageName, querryInfo)
      // console.log(querryInfo)

      const { totalCount, list } = pageListRes.data
      // console.log(pageListRes.data)

      this.pageList = list
      this.pageTotalCount = totalCount
      // console.log(list)
    },

    // 删除
    async deletePageByIdAction(pageName: string, id: number) {
      const deleteRes = deletePageById(pageName, id)

      // 刷新页面
      this.postPageListAction(pageName, { offset: 0, size: 10 })
    },

    // 增加数据
    async newPageDataAction(pageName: string, pageInfo: any) {
      const newResult = await newPageData(pageName, pageInfo)
      // console.log(newResult)

      // 刷新页面
      this.postPageListAction(pageName, { offset: 0, size: 10 })

      // 获取完整的数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },

    // 改数据
    async editPageDataAction(pageName: string, id: number, pageInfo: any) {
      const newResult = await editPageData(pageName, id, pageInfo)
      // console.log(newResult)

      // 刷新页面
      this.postPageListAction(pageName, { offset: 0, size: 10 })

      // 获取完整的数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    }
  }
})

export default useSystemStore
